package com.baike.shiro;

import com.baike.entity.TbStudent;
import com.baike.mapper.TbStudentMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/*
*自定义 Realm类 需要继承AuthorizingRealm类
* */
public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private TbStudentMapper studentMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法.....");
        return null;
    }

//  认证方法  调用subject的login方法的时候会进入
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        String username = "admin";
//        String password = "212b0748f7bbdd42bb4b67ffef10b259";
//        String salt = "1b45f3";
        System.out.println("进入认证方法.....");
//        执行登陆逻辑
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        TbStudent tbStudent = studentMapper.selectByName(token.getUsername());
        if (tbStudent == null){
            throw new UnknownAccountException("此账户不存在");
        }

//      第一个参数是 登陆成功后放入session中的对象,第二个参数是 数据库中的密码  第三个参数是  用户名(账号)
        return new SimpleAuthenticationInfo(tbStudent,tbStudent.getStudentPassword(), ByteSource.Util.bytes(tbStudent.getStudentSalt()),tbStudent.getStudentAccount());
    }
}
